<template>
	<div id="record_container">
		<div id="record_btn" @click="clickBtn" v-show="!localId"></div>
		<pop :popshow="popshow" :popstyle="popstyle">
			<div id="record" :class="{isRecording: isRecording}">
				<canvas :width="canvasWid*remToPx" :height="canvasWid*remToPx"></canvas>
				<div id="canvas_cover" @touchstart="clickRecord" @touchend="clickRecord" @contextmenu.prevent>
					<span v-show="!isRecording"
					>长按开始</span>
					<span v-show="isRecording">
						松开结束
						<p>{{countdown.s}} s</p>
					</span>
				</div>
			</div>
		</pop>
		<div id="play_container" v-show="localId">
			<div id="play_bar" :class="{isPlay: isPlay}"
			:style="{width: audioWid}"
			@click="playAudio">
				{{countdown.s}} s
			</div>
			<div id="play_remove" class="c-btn"
			@click="remove">删除录音</div>
		</div>
	</div>
</template>
<script>
import pop from '../Pop'
import {myAlert, myHttp} from '../assets/js/utils.js'
import {appId, baseURL} from '../assets/js/global.js'
export default{
	name:'recordaudio',
	data(){
		return{
			popshow: false,
			popstyle:{
				width:'2.6rem',
				height: '2.6rem'
			},
			isRecording: false,
			remToPx:1,
			canvas: '',
			canvasWid: 2.8,
			ctx:'',
			countdown:{
				start:'',
				req:'',
				s:60,
				end: ''
			},
			localId: '',
			audioWid: '',
			isPlay: false
		}
	},
	mounted(){
		this.remToPx = document.getElementsByTagName('html')[0].style.fontSize.slice(0,-2);
		myHttp('getJsApiTicket.do', {
			url: location.href.split('#')[0]
		}).then(r => {
			console.log(r);
			wx.config({
				// debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: appId, // 必填，公众号的唯一标识
				timestamp: r.timestamp,
				nonceStr: r.nonceStr,
				signature: r.signature,
				jsApiList: ['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice']
			});
		})
	},
	methods:{
		drawCurve(ms){
			let r = ms/30000;

			let canvas = this.canvas, ctx = this.ctx;
			let wid = canvas.width/2;
			ctx.clearRect(0,0,wid, wid);
			ctx.beginPath();
			ctx.arc(wid,wid,wid,-0.5*Math.PI,(-.5+r)*Math.PI);
			ctx.lineTo(wid,wid);
			ctx.lineTo(wid,0);
			ctx.fillStyle='#6db1ff';
			ctx.fill();
		},
		cb(){
			let now = new Date().getTime();
			let t = now - this.countdown.start;
			this.countdown.s = Math.floor( t / 1000);
			this.drawCurve(t);
			if(t >= 59*1000) this.end();
			else this.req = requestAnimationFrame(this.cb);
		},
		clear(){
			cancelAnimationFrame(this.req);
			canvas.clearRect(0,0,this.canvas.width, this.canvas.height);
			this.countdown.s = 60;
		},
		start(){
			this.countdown.start = new Date().getTime();
			this.req = requestAnimationFrame(this.cb);
			wx.startRecord();
		},
		end(){
			const self = this;
			this.popshow = false;
			cancelAnimationFrame(this.req);
			wx.stopRecord({
			    success(res) {
			        const localId = res.localId;
			        self.localId = localId;
			        self.audioWid =  1 + self.countdown.s/10+'rem';
			        wx.uploadVoice({
			            localId: localId,
			            isShowProgressTips: 1, // 默认为1，显示进度提示
			            success: function (res) {
			                var serverId = res.serverId;
			                self.$emit('recordId', serverId);
			            }
			        });
			    }
			});
		},
		clickRecord(){
			if(!this.isRecording) {
				this.start();
				myAlert.small('开始录音..');
			}
			else {
				this.end();
				myAlert.small('结束录音');
			}
			this.isRecording = !this.isRecording;
		},
		clickBtn(){
			this.popshow = true;
			this.$nextTick(() => {
				this.canvas = document.getElementsByTagName('canvas')[0];
				this.ctx = this.canvas.getContext('2d');
			})
		},
		play(){
			wx.playVoice({
			    localId: this.localId
			});
			myAlert.small('开始播放')
		},
		pause(){
			wx.stopVoice({
			    localId: this.localId
			});
			myAlert.small('停止播放');
		},
		playAudio(){
			const self = this;
			if(!this.isPlay) {
				this.play();
				wx.onVoicePlayEnd({
				    success() {
				        myAlert.small('播放完毕')
				        self.isPlay = false;
				    }
				});
			}
			else this.pause();
			this.isPlay = !this.isPlay;
		},
		remove(){
			this.localId = '';
			this.$emit('recordId', '');
		}
	},
	components:{pop}
}
</script>
<style lang='less' scoped>
	@baseColor: #6db1ff;
	#record_container{
		height: .7rem;
	}
	#record_btn{
		float: right;
		width: .6rem;
		height: .7rem;
		background: url(.././assets/img/icon_yuyin.png) center no-repeat;
		border-radius: 100%;
		background-size: contain;
	}
	#record{
		width: 100%;
		height: 100%;
		position: relative;
		transition: all .3s;
		&.isRecording{
			transform: scale(1.07);
		}
		canvas{
			position: absolute;
			top: -.1rem;
			left: -.1rem;
		}
		#canvas_cover{
			width: 100%;
			height: 100%;
			position: absolute;
			top:0;
			left: 0;
			background: #fff;
			border-radius: 100%;
			display: flex;
			user-select: none;
			span{
				margin: auto;
			}
			p{
				margin-top: .2rem;
				line-height: .2rem;
			}
			p,span{
				color: @baseColor;
				text-align: center;
			}
		}
	}
	#play_container{
		overflow: hidden;
		#play_bar{
			float: left;
			min-width: 1.5rem;
			max-width: 7rem;
			height: 0.64rem;
			border-radius: 0.05rem;
			display: inline-block;
			background: url(.././assets/img/yuyin.png) no-repeat .2rem center;
			background-size: 0.32rem 0.4rem;
			background-color: #6db1ff;
			padding-left: .7rem;
			color: #fff;
			font-size: .3rem;
			line-height: .64rem;
			&.isPlay{
				background-image: url(.././assets/img/yuyin2.gif);
			}
		}
		#play_remove{
			float: right;
			width: 1.8rem;
			font-size: .28rem;
			margin-top: .1rem;
		}
	}
</style>